package com.free.mini.admin.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.free.mini.common.base.ResultData;

import lombok.extern.slf4j.Slf4j;

/**
 * @author dongsufeng
 * @version 4.0
 * @date 2023/8/21 16:01
 */
@RestController
@Slf4j
@RequestMapping("api/admin/v1/")
public class FileUploadController {

    @PostMapping("upload/file")
    public ResultData upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file){
        log.info("==========upload");
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File("/data/logs/upload");
        //创建文件
        File destFile = new File("/data/logs/upload/"+ newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url","/api/admin/upload/" + newFileName);
            return ResultData.data(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error("文件上传失败");
        }
    }
}
